using Serilog;
using SqlSugar;

namespace _RobotInspection.Extensions
{
    /// <summary>
    /// Sqlsugar扩展类
    /// </summary>
    public static class SqlsugarSetup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services">服务</param>
        /// <param name="configuration">配置文件</param>
        /// <param name="dbName">数据库名称</param>
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,string dbName = "db_master")
        {
            var connectionString = configuration.GetConnectionString(dbName);
            Log.Information($"正在初始化数据库连接: {dbName}, 连接字符串: {connectionString}");
            
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                ConfigId = dbName, // 添加这行来设置ConfigId
                DbType = SqlSugar.DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = true,
                    IsWithNoLockQuery = true
                }
            },
            db =>
            {
                //单例参数配置，所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    // Console.WriteLine(sql);//输出sql
                };

                // 添加错误日志记录
                db.Aop.OnError = (exp) =>
                {
                    // 这里可以添加日志记录
                    Log.Error(exp, $"SQL执行错误：{exp.Message}");
                };

                // 添加连接测试
                try
                {
                    Log.Information("正在测试数据库连接...");
                    db.Open();
                    Log.Information("数据库连接测试成功");
                    db.Close();
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"数据库连接测试失败: {ex.Message}");
                    throw new Exception($"数据库连接测试失败: {ex.Message}", ex);

                }
            });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }
}